#include "UP_ADC.h"
#include "UP_GPIO.h"
#include "gd32f4xx.h"
#include "systick.h"
#include <stdio.h>

/* ADC初始化 */
void ADC_init(uint32_t adc)
{
    UP_ADC_PARAMS params = {
        .prescaler = ADC_ADCCK_PCLK2_DIV8,
        .sync_mode = ADC_SYNC_MODE_INDEPENDENT,
        .cont_mode = DISABLE,
        .scan_mode = DISABLE,
        .data_align = ADC_DATAALIGN_RIGHT,
        .channel_len = 1U,
    };
    ADC_init_with_params(adc, &params);

}
/* ADC初始化 */
void ADC_init_with_params(uint32_t adc, UP_ADC_PARAMS *params)
{
    /* adc 引脚初始化 */
    switch (adc) {
        case ADC0:
            /* enable ADC0 clock */
            rcu_periph_clock_enable(RCU_ADC0);
            break;
        case ADC1:
            /* enable ADC1 clock */
            rcu_periph_clock_enable(RCU_ADC1);
            break;
        case ADC2:
            /* enable ADC2 clock */
            rcu_periph_clock_enable(RCU_ADC2);
            break;
        default:
            break;
    }
    /* config ADC clock */
    adc_clock_config(params->prescaler);
    /* reset ADC */
    adc_deinit();
    /* configure the ADC  mode */
    adc_sync_mode_config(params->sync_mode); // 所有ADC都工作在独立模式

    /* ADC contineous function disable */
    adc_special_function_config(adc, ADC_CONTINUOUS_MODE, params->cont_mode); // 关闭连续模式
    /* ADC scan mode disable */
    adc_special_function_config(adc, ADC_SCAN_MODE, params->scan_mode); // 关闭扫描模式

    /* ADC data alignment config */
    adc_data_alignment_config(adc, params->data_align); // LSB对齐，低位对齐

    /* ADC channel length config */
    adc_channel_length_config(adc, ADC_ROUTINE_CHANNEL, params->channel_len); //  ADC规则通道 长度为1

    /* enable ADC interface */
    adc_enable(adc);
    /* wait for ADC stability */
    delay_1ms(1);
    /* ADC calibration and reset calibration */
    adc_calibration_enable(adc); // ADC校准
    /* wait for ADC stability */
    delay_1ms(1);
}
/*!
    \brief      ADC channel sample  ADC通道采样
    \param[in]  none
    \param[out] none
    \retval     none
*/
uint16_t adc_channel_sample(uint32_t adc, uint8_t channel)
{
    /* ADC regular channel config */
    adc_routine_channel_config(adc, 0U, channel, ADC_SAMPLETIME_15); // 15个采样周期
    /* ADC software trigger enable */
    adc_software_trigger_enable(adc, ADC_ROUTINE_CHANNEL); // ADC软件触发使能

    /* wait the end of conversion flag */
    while (!adc_flag_get(adc, ADC_FLAG_EOC))
        ;
    /* clear the end of conversion flag */
    adc_flag_clear(adc, ADC_FLAG_EOC);
    /* return regular channel sample value */
    return (adc_routine_data_read(adc));
}

/* 遥感扫描函数 */
uint16_t ADC_scan(uint32_t adc, uint8_t channel)
{
    return adc_channel_sample(adc, channel);  // 采样
}